package com.yuncheng.spcyApi.spcyService;

import cn.hutool.core.collection.CollectionUtil;
import com.yuncheng.spcyApi.selectXzxkApi.constant.PutZwxtConstant;
import com.yuncheng.spcyApi.selectXzxkApi.service.PutZwxtService;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.busService.InitWjjlService;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.schedule.ScheduleConstant;
import com.yuncheng.spcyApi.constant.sys.SysConfigConstant;
import com.yuncheng.spcyApi.constant.wjml.WjmlConstant;
import com.yuncheng.spcyApi.flow.*;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.scheduleJob.ScheduleJobService;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.spcyApi.vo.sqsx.SqsxZzZyYbNumVo;
import com.yuncheng.spcyApi.vo.wj.WjjlVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Component(value = "spcyVerifyService")
public class SpcyVerifyService {

    private static final Logger log = LoggerFactory.getLogger(SpcyVerifyService.class);

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    @Lazy
    private ScheduleJobService scheduleJobService;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    @Lazy
    private SpcyFlfgService spcyFlfgService;

    @Resource
    @Lazy
    private ISpcySqsxWjmlService spcySqsxWjmlService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private InitWjjlService initWjjlService;

    @Resource
    private SqsxYwxxInfoService spcySqsxYwxxService;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private XpryTimedTasksService xpryTimedTasksService;

    @Resource
    private SpcyHbjcService spcyHbjcService;

    @Resource
    private SpcyQyInfoService spcyQyInfoService;

    @Resource
    private ISpcyRsWjmbZjmlService spcyRsWjmbZjmlService;

    @Resource
    private SpcyQyFlowService spcyQyFlowService;

    @Resource
    @Lazy
    private PutZwxtService putZwxtService;

    /** 是否开启同步政务服务事项 */
    private boolean verifyEnableSyncSqsx(){
        String code = Optional.ofNullable(sysConfigService.getSysConfigByCode(SysConfigConstant.SYNC_ZWFWXT_SQSX)).orElseGet(()->"0");
        if (code.equals("0")){
            return false;
        }else {
            return true;
        }
    }

    /** 推送申请事项-受理信息-政务服务系统 */
    private void putSqsxRwslToZwfwxt(String sqsxid){
        if (!verifyEnableSyncSqsx()){
            return;
        }

        boolean isFlag = this.verifySqsxIsXzspData(sqsxid, null);
        if (isFlag) {
            scheduleJobService.pushXzspDataByJkType(sqsxid, ScheduleConstant.Xzsp_Data_Rwsl_Code);
        }
    }

    /** 推送申请事项相关内容-政务服务系统 */
    private void putSqsxToZwfwxt(String sqsxid, SpcySqsxBasic sqsx){
        if (!verifyEnableSyncSqsx()){
            return;
        }

        // 是否属于行政审批数据
        boolean isFlag = this.verifySqsxIsXzspData(sqsxid, sqsx);
        if (isFlag){
            scheduleJobService.pushXzspDataByJkType(sqsxid,ScheduleConstant.Xzsp_Data_Fjcl_Code);
            scheduleJobService.pushXzspDataByJkType(sqsxid,ScheduleConstant.Xzsp_Data_Lzjl_Code);
            scheduleJobService.pushXzspDataByJkType(sqsxid,ScheduleConstant.Xzsp_Data_Scjl_Code);
        }
    }

    /**
     * 验证审评查验流程-任务受理环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     * @param flowVo 流程提交参数
     */
    public void verifySpcyFlowNodeRwsl(String sqsxid, String submitType, boolean isSubmitFront, FlowVo flowVo){
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)){
            return;
        }

        if (isSubmitFront){
            if (StringUtils.isBlank(flowVo.getDbrid())){
                throw new BusinessException("请选择办理人！");
            }

            String zbrmc = busService.getZbrmcByZbrId(flowVo.getDbrid());
            spcySqsxBaiscService.updateSqsxZbr(sqsxid, flowVo.getDbrid(), zbrmc);

        }

        if (!isSubmitFront) {

//            this.verifyClscNumberJobInBkb(flowVo.getDbrid());

            // 推送受理信息 // 是否属于行政审批数据
            /*boolean isFlag = this.verifySqsxIsXzspData(sqsxid, null);
            if (isFlag) {
                scheduleJobService.pushXzspDataByJkType(sqsxid, ScheduleConstant.Xzsp_Data_Rwsl_Code);
            }*/
//            this.putSqsxRwslToZwfwxt(sqsxid);

            /** 生成企业账号并绑定 */
            String fqyid = spcySqsxBaiscService.selectFqyidById(sqsxid);
            spcyQyInfoService.addUserQy(fqyid);

        }

    }

    /**
     * 验证审评查验流程-材料审查环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     * @param job 当前流程任务
     */
    public void verifySpcyFlowNodeClsc(FlowVo flowVo, String sqsxid, String submitType, boolean isSubmitFront, SpcySqsxJob job) {
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)) {
            return;
        }

        if (isSubmitFront) {
            if (StringUtils.isBlank(flowVo.getFclscms())){
                throw new BusinessException("请选择提交类型！");
            }

            // 更新申请事项-材料审查模式
            spcySqsxBaiscService.updateSqsxByClscms(sqsxid, flowVo.getFclscms());
        }

        if (!isSubmitFront){
//            this.verifyClscNumberJobInKb(job.getFdbrid());
        }
    }

    /**
     * 验证审评查验流程-材料审查复核环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     * @param sqsx 申请事项
     */
    public void verifySpcyFlowNodeClscFh(String sqsxid, String submitType, boolean isSubmitFront, SpcySqsxBasic sqsx) {
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)) {
            return;
        }

        if (isSubmitFront) {

        }

        if (!isSubmitFront){

        }
    }

    /**
     * 验证审评查验流程-任务分配环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     * @param flowVo 流程提交参数
     */
    public void verifySpcyFlowNodeRwfp(String sqsxid, String submitType, boolean isSubmitFront, FlowVo flowVo) {
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)) {
            return;
        }

        if (isSubmitFront){
            if (StringUtils.isBlank(flowVo.getDbrid())){
                throw new BusinessException("请选择办理人！");
            }

            String zbrmc = busService.getZbrmcByZbrId(flowVo.getDbrid());
            spcySqsxBaiscService.updateSqsxZbr(sqsxid, flowVo.getDbrid(), zbrmc);
        }

    }

    /**
     * 验证审评查验流程-方案制作环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     */
    public void verifySpcyFlowNodeFazz(String sqsxid, String submitType, boolean isSubmitFront, SpcySqsxJob job){
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)){
            return;
        }

        if (isSubmitFront) {
            /** 20240424 */
            /*List<SpcySqsxXpjl> tyXpXpjlList = busService.getTyXpXpjlList(sqsxid, SpcyConstant.FLOW_TYPE_CY);
            if (CollectionUtils.isEmpty(tyXpXpjlList)) {
                throw new BusinessException("请选择【同意】选派的现场检查人员！");
            }
            this.verifyXcjcIsExistsTyXpZz(tyXpXpjlList); // 验证是否存在组长*/

            /** 验证同意选派人数是否满足 */
//            this.verifyFazzXptyRyNum(sqsxid);

            /** 验证相关文件材料是否存在 */
//            this.verifyFazzFileIsExists(null,sqsxid);

            /** 验证合并事项是否都绑定的检查报告 */
//            spcyHbjcService.verifyHbsxIsExistNotBdBgMbSx(sqsxid);

        }

        if (!isSubmitFront){

            // 更新申请事项-查验方案状态
//            this.updateSqsxFazzCyfazt(sqsxid);

            // 更新未确认选派人员工作状态
            this.updateSqsxWqrXpryGzzt(sqsxid);

            // 将不可办改为可办
//            this.verifyClscNumberJobInKb(job.getFdbrid());

            // 提前结束-执行中的自动抽选任务列表
            xpryTimedTasksService.tjEndZxzAutoXpryRwList(sqsxid);

        }

    }

    /**
     * 验证审评查验流程-方案审批环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     */
    public void verifySpcyFlowNodeFasp(String sqsxid, String submitType, SpcySqsxJob job, boolean isSubmitFront){
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)){
            return;
        }

        if (isSubmitFront) {
            /*List<SpcySqsxXpjl> tyXpXpjlList = busService.getTyXpXpjlList(sqsxid, SpcyConstant.FLOW_TYPE_CY);
            if (CollectionUtils.isEmpty(tyXpXpjlList)) {
                throw new BusinessException("请选择【同意】选派的人员！");
            }*/

        }

        if (!isSubmitFront) {
            //  busService.sendSmsAndEmailToHcyGcyQy(sqsxid); // 发检查员、观察员、企业通知相关的函

            /** 验证是否为合并事项 */
            SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
            boolean isHbsx = spcyHbjcService.verifySqsxIsHbsqsx(sqsxid, sqsx);

            /** 初始化现场检查章节 */
            if (isHbsx){
                /** 合并事项 */
                if (StringUtils.isNotBlank(sqsx.getFhbsxids())) {
                    for (String sxid : StringPatternUtils.getListByIds(sqsx.getFhbsxids())) {
                        List<SpcyRsWjmbZjml> wjmbZjmlList = spcyRsWjmbZjmlService.selectZjByHbsxId(sqsxid, sxid);
                        if (CollectionUtil.isNotEmpty(wjmbZjmlList)) {
                            spcyFlfgService.initWjmbZjGenXcjczj(wjmbZjmlList, sqsx, sxid);
                        }
                    }
                }

            }else {
                /** 单个事项 */
                List<SpcyRsWjmbZjml> wjmbZjmlList = spcyRsWjmbZjmlService.selectWjmbZjmlList(sqsxid);
                spcyFlfgService.initWjmbZjGenXcjczj(wjmbZjmlList, sqsx, sqsxid);
            }

            /** 方案及相关文件自动盖章 */
            initWjjlService.verifyAutoFileGzByFazd(sqsxid);
            /*try {
                spcyQyFlowService.addJbryztxJob(sqsx, sqsxid, job, false, "");
            }catch (Exception e){
                log.error("方案及相关文件自动盖章错误：{}", e.getMessage());
            }*/

            /** 初始化-日常考评、检查员互评、见习考评流程 */
            spcySqsxYwxxService.initJcyRckpOrYbkpOrHp(sqsxid, sqsx);

            /** 新增企业现场检查 */
//            spcyQyFlowService.addQyXcjcJob(job, sqsxid, sqsx.getFqyid(), sqsx.getFqymc());

            /** 验证是否为合并事项 */
            if (isHbsx){
                /** 同步信息 */
                spcyHbjcService.ffSyncHbsxInfoByFasp(sqsxid, sqsx);
            }

        }
    }

    /**
     * 验证审评查验流程-现场检查环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     */
    public void verifySpcyFlowNodeXcjc(FlowVo flowVo, String sqsxid, String submitType, boolean isSubmitFront, SpcySqsxBasic sqsx) {
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)) {
            return;
        }

        if (sqsx == null){
            sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
        }

        if (isSubmitFront){

            // 验证是否为检查员组长
            /*CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
            if (!verifyNowUserIsXpryZz(sqsxid, currentUser.getId())){
                throw new BusinessException("提交失败，当前没有权限！只有组长存在权限！");
            }*/

            /** 是否发起整改 */
            /*if (StringUtils.isNotBlank(flowVo.getSffqzg()) && flowVo.getSffqzg().equals("是")){
                if (StringUtils.isBlank(flowVo.getFzgyj())){
                    throw new BusinessException("整改意见为空！");
                }
            }*/

            // 验证现场检查章节-是否全部完成
//            boolean isHbsx = spcyHbjcService.verifySqsxIsHbsqsx(sqsxid, sqsx);
            boolean isHbsx = true;
            if (isHbsx){
                /** 合并事项 */


            }else {
//                spcyFlfgService.verifyXcjczjWczt(sqsxid, sqsx, null);

                // 验证检查情况专述
//                this.verifyXcjcZs(sqsx, sqsxid);

                // 验证检查结论
//                this.verifyXcjcJl(sqsx, sqsxid);

                // 验证现场检查环节-对应的文件目录是否已经都上传文件
//                this.verifyXcjcFileIsExists(sqsx, sqsxid);

                // 验证问题及条款是否必填
    //            spcyFlfgService.verifyXcjcWtAndTkEmpty(sqsxid);
            }

        }

        if (!isSubmitFront) {

            /** 更新查验状态 */
            this.updateSqsxXcjcCywczt(sqsxid);

            /** 发起整改 */
//            putZwxtService.pushQyZgNotice(flowVo, sqsxid);

            /** 验证是否合并事项 */
            /*boolean isHbsx = spcyHbjcService.verifySqsxIsHbsqsx(sqsxid, sqsx);
            if (isHbsx) {
                *//** 合并事项 *//*
                *//** 同步相关信息 *//*
                spcyHbjcService.ffSyncHbsxInfoByXcjc(sqsxid, sqsx);
            }*/

            /** 办结企业现场检查 */
//            spcyQyFlowService.bjQtXcjcJob(sqsxid, sqsx);

        }
    }

    /**
     * 验证审评查验流程-综合评定环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     */
    public void verifySpcyFlowNodeZhpd(String sqsxid, String submitType, boolean isSubmitFront, FlowVo flowVo) {
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)) {
            return;
        }

        if (isSubmitFront){
            if (StringUtils.isBlank(flowVo.getDbrid())){
                throw new BusinessException("请选择办理人！");
            }

            if (StringPatternUtils.getListByIds(flowVo.getDbrid()).size() < 2){
                throw new BusinessException("请选择至少两个办理人！");
            }
        }
    }

    /**
     * 验证审评查验流程-综合评定复核环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     * @param flowVo 流程提交参数
     */
    public void verifySpcyFlowNodeZhpdFh(String sqsxid, String submitType, boolean isSubmitFront, FlowVo flowVo){
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)){
            return;
        }

        if (isSubmitFront){

        }else {

        }



    }

    /**
     * 验证审评查验流程-移送确认环节
     * @param isSubmitFront true: 提交前；false: 提交后
     */
    /**
     * 验证审评查验流程-移送确认环节
     * @param sqsxid 申请事项id
     * @param submitType 0：保存；1:提交
     * @param isSubmitFront true: 提交前；false: 提交后
     */
    public void verifySpcyFlowNodeYsrq(String sqsxid, String submitType, boolean isSubmitFront) {
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)) {
            return;
        }

        // 提交前校验
        if (isSubmitFront) {
            // 验证-行政审批-数据-移送环节-是否保存经办人
//            this.verifySqsxIsSaveYsr(sqsxid);
        }

        // 提交后校验
        if (!isSubmitFront){

            /** 更新申请事项移送状态 */
            spcySqsxBaiscService.updateSqsxInYs(sqsxid);

            /** 文件盖章 */
            initWjjlService.verifyAutoFileGzByYsqr(sqsxid);

            /** 是否属于行政审批数据 */
            /*boolean isFlag = this.verifySqsxIsXzspData(sqsxid,sqsx);
            if (isFlag){
                scheduleJobService.pushXzspDataByJkType(sqsxid,ScheduleConstant.Xzsp_Data_Fjcl_Code);
                scheduleJobService.pushXzspDataByJkType(sqsxid,ScheduleConstant.Xzsp_Data_Lzjl_Code);
                scheduleJobService.pushXzspDataByJkType(sqsxid,ScheduleConstant.Xzsp_Data_Scjl_Code);
            }*/
//            this.putSqsxToZwfwxt(sqsxid, null);

            /** 定时任务-删除启动minio存储，删除本地文件 */
//            scheduleJobService.deleteSqsxLocalWjjlSchedule(sqsxid);

            /** 将本地事项文件模板推送到文件桶 */
//            initWjjlService.pushYsSqsxWjmbToFileBucket(sqsxid);
        }

    }

    /**
     * 验证审评查验流程-综合评定环节跳转
     */
    public void verifySpcyFlowJumpZhpdNode(String sqsxid){

        LambdaUpdateWrapper<SpcySqsxBasic> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(SpcySqsxBasic::getId, sqsxid);

        SpcySqsxBasic updateSqsx = new SpcySqsxBasic();
        updateSqsx.setFcywczt("是");
        spcySqsxBaiscService.update(updateSqsx, updateWrapper);

        busService.updateCyUserGzzt(sqsxid); // 更新人员工作状态
    }

    /**
     * 验证现场检查-选派人员-是否存在同意选派的组长人员
     * 不存在，抛出问题
     * @param tyxpjlList 同意选派人员列表
     */
    public void verifyXcjcIsExistsTyXpZz(List<SpcySqsxXpjl> tyxpjlList){
        if (CollectionUtils.isNotEmpty(tyxpjlList)){
            boolean isExistZz = false;

//            StringBuilder wrqLog = new StringBuilder();
            for (int i=0; i<tyxpjlList.size(); i++){

                /*if (StringUtils.isBlank(tyxpjlList.get(i).getFsftyxp())
                        || tyxpjlList.get(i).getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_WQY)){
                    wrqLog.append(tyxpjlList.get(i).getFssk()).append("[").append(tyxpjlList.get(i).getFjcyxm()).append("]");
                }*/

                if (StringUtils.isNotBlank(tyxpjlList.get(i).getFssk()) && tyxpjlList.get(i).getFssk().contains(SpcyConstant.HCY_SSK_ZZ)){
                    isExistZz = true;
                    break;
                }
            }

            /*if (!StringPatternUtils.verifryIsEmptyStringBuilder(wrqLog)){
                throw new BusinessException("存在未确认选派人员：" + wrqLog.toString());
            }*/

            if (!isExistZz){
                throw new BusinessException("请至少选派一名【同意】选派的组长！");
            }
        }
    }

    /**
     * 验证当前用户-是否为选派人员-是否为组长
     * @param sqsxid 申请事项id
     * @param userid 用户id
     * @return true: 为组长
     */
    public boolean verifyNowUserIsXpryZz(String sqsxid,String userid){
        List<SpcySqsxXpjl> list = spcySqsxXpjlService.list(new LambdaQueryWrapper<SpcySqsxXpjl>()
                .eq(SpcySqsxXpjl::getFsqsxid, sqsxid)
                .eq(SpcySqsxXpjl::getFuserid, userid)
                .like(SpcySqsxXpjl::getFssk, SpcyConstant.HCY_SSK_ZZ));
        if (CollectionUtil.isNotEmpty(list)){
            return true;
        }

        return false;
    }

    /**
     * 获取申请事项选派组长列表
     * @param sqsxid 申请事项id
     */
    public List<SpcySqsxXpjl> querySqsxXpZzList(String sqsxid){
        return spcySqsxXpjlService.getSqsxXpZzList(sqsxid);
    }

    /**
     * 验证-行政审批-数据-移送环节-是否保存经办人
     */
    public void verifySqsxIsSaveYsr(String sqsxid){

        if (!verifyEnableSyncSqsx()){
            return;
        }

        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
        if (sqsx != null && StringUtils.isNotBlank(sqsx.getFxzspzt())
                && sqsx.getFxzspzt().equals(SpcyConstant.SQSX_BASIC_XZSPZT_YES)){
            if (StringUtils.isBlank(sqsx.getFxzspysrid())){
                throw new BusinessException("请先选择业务部门经办人！");
            }
        }
    }

    /**
     * 判断申请-是否为行政审批-数据
     */
    public boolean verifySqsxIsXzspData(String sqsxid, SpcySqsxBasic sqsxBasic){
        SpcySqsxBasic sqsx = null;
        if (sqsxBasic != null){
            sqsx = sqsxBasic;
        }else {
            sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
        }

        if (sqsx == null){
            return false;
        }
        if (StringUtils.isBlank(sqsx.getFxzspzt())){
            return false;
        }

        if (sqsx.getFxzspzt().equals(SpcyConstant.SQSX_BASIC_XZSPZT_YES)){
            if (StringUtils.isNotBlank(sqsx.getFlczt())){
                if (sqsx.getFlczt().equals(PutZwxtConstant.SQSX_LCZT_FZXBLSX)) {
                    return false;
                }else if (sqsx.getFlczt().equals(PutZwxtConstant.SQSX_LCZT_QYCJ)){
                    return false;
                }
            }
            return true;
        }

        return false;
    }

    /**
     * 将材料审查环节-流程任务进行权限校验
     * 同一个人-同一个环节-待办数量
     * 数量 >3 后面进来的待办都进行排队，不可办
     */
    public void verifyClscNumberJobInBkb(String dbrid){

        List<SpcySqsxJob> dbList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .like(SpcySqsxJob::getFdbrid, dbrid)
                .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_FAZZ)
                .orderByAsc(SpcySqsxJob::getFfssj));

        int totalSize = dbList.size(); // 总的待办数量
        int maxSize = 3; // 最大数量

        // 总数量 大于 最大值
        if (totalSize > maxSize){
            int slSize = totalSize - maxSize; // 多出来的数量

            // 将多余的数量改为不可办
            for (int i=0; i<slSize; i++) {
                SpcySqsxJob job = dbList.get(maxSize + i);
                if (StringUtils.isBlank(job.getFlcsfkb()) || job.getFlcsfkb().equals(SpcyFlowConstant.JOB_LCSFKB_KB)) {
                    job.setFlcsfkb(SpcyFlowConstant.JOB_LCSFKB_BKB);
                    spcySqsxJobService.updateById(job);
                }
            }
        }

    }

    /**
     * 将材料审查环节-流程任务进行权限校验
     * 同一个人-同一个环节-待办数量
     * 数量 > 3 将前三条改为 可办
     */
    public void verifyClscNumberJobInKb(String dbrid){

        List<SpcySqsxJob> kbList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .like(SpcySqsxJob::getFdbrid, dbrid)
                .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_FAZZ)
                .orderByAsc(SpcySqsxJob::getFfssj));

        int kbTotalSize = kbList.size(); // 待办总数量
        int kbMaxSize = 3; // 最大数量
        int kbUpdateSize = 0; // 可办更新数量

        // 可办更新数量 = (总量 > 最大 = 最大)或者 ( 总量 < 最大 = 总量)
        kbUpdateSize = kbTotalSize > kbMaxSize ? kbMaxSize : kbTotalSize;


        for (int i=0; i<kbUpdateSize; i++){
            SpcySqsxJob job = kbList.get(i);
            if (StringUtils.isNotBlank(job.getFlcsfkb()) && job.getFlcsfkb().equals(SpcyFlowConstant.JOB_LCSFKB_BKB)) {
                job.setFlcsfkb(SpcyFlowConstant.JOB_LCSFKB_KB);
                spcySqsxJobService.updateById(job);
            }
        }

    }

    /**
     * 验证是否能够批量提交-流程任务
     * @param jobids
     * @return
     */
    public void verifySfpltj(String jobids){
        if (StringUtils.isBlank(jobids)){
            throw new BusinessException("请选择待办数据！");
        }
        List<String> jobIdList = StringPatternUtils.getListByIds(jobids);
        List<SpcySqsxJob> jobList = spcySqsxJobService.listByIds(jobIdList);

        String firstHjmc = ""; // 第一个环节名称

        // 验证选择的流程任务-环节是否处于同一结点
        for (int i=0; i<jobList.size(); i++){
            /*if (!jobList.get(i).getFhjmc().equals(SpcyFlowConstant.HJMC_RWSL)){
                throw new BusinessException("只有处于【任务受理】环节才能够批量提交！");
            }*/

            if (i==0){
                firstHjmc = jobList.get(0).getFhjmc();
            }else {
                if (!firstHjmc.equals(jobList.get(i).getFhjmc())){
                    throw new BusinessException("请选择处于同一环节的待办数据！");
                }
            }
        }
    }

    /**
     * 验证是否能够批量退回政务系统
     * @param jobids
     * @return
     */
    public void verifySfplthzwxt(String jobids){
        if (StringUtils.isBlank(jobids)){
            throw new BusinessException("请选择待办数据！");
        }
        List<String> jobIdList = StringPatternUtils.getListByIds(jobids);
        List<SpcySqsxJob> jobList = spcySqsxJobService.listByIds(jobIdList);
        for (int i=0; i<jobList.size(); i++){
            if (!jobList.get(i).getFhjmc().equals(SpcyFlowConstant.HJMC_RWSL)){
                throw new BusinessException("只有处于【任务受理】环节才能够退回到政务系统！");
            }
        }
    }

    /**
     * 验证是否能够批量内部转办
     * @param jobids
     * @return
     */
    public void verifySfplnbzb(String jobids){
        if (StringUtils.isBlank(jobids)){
            throw new BusinessException("请选择待办数据！");
        }
        List<String> jobIdList = StringPatternUtils.getListByIds(jobids);
        List<SpcySqsxJob> jobList = spcySqsxJobService.listByIds(jobIdList);
        for (int i=0; i<jobList.size(); i++){
            if (!jobList.get(i).getFhjmc().equals(SpcyFlowConstant.HJMC_RWSL)){
                throw new BusinessException("只有处于【任务受理】环节才能够转到其他科室！");
            }
        }

    }

    /**
     * 验证当前流程任务是否为【现场检查】环节
     * @return true: 为现场检查
     */
    public boolean verifyNowJobInXcjcNode(String sqsxid){
        List<SpcySqsxJob> list = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_XCJC)
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.LCMC_LIKE_SPCYLC)
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB));
        if (CollectionUtil.isNotEmpty(list)){
            return true;
        }

        return false;
    }

    /**
     * 验证现场检查专述
     */
    private void verifyXcjcZs(SpcySqsxBasic sqsx, String sqsxid){
        if (sqsx == null){
            sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
        }
        if (sqsx != null && StringUtils.isBlank(sqsx.getFjcqkzs())){
            throw new BusinessException("请填写检查情况描述！");
        }

    }

    /**
     * 验证现场检查结论
     */
    private void verifyXcjcJl(SpcySqsxBasic sqsx, String sqsxid){
        if (sqsx == null){
            sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
        }

        if (sqsx != null && StringUtils.isBlank(sqsx.getFcyjl())){
            throw new BusinessException("请填写检查结论！");
        }
    }

    /**
     * 验证现场检查环节-对应的文件目录是否已经都上传文件
     */
    private void verifyXcjcFileIsExists(SpcySqsxBasic sqsx,String sqsxid){
        if (sqsx == null){
            sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
        }
        if (sqsx == null){
            return;
        }
        String fywflcode = sqsx.getFywflcode();


        // 现场检查-必填目录
        LambdaQueryWrapper<SpcySqsxWjml> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxWjml::getFywflcode, fywflcode);
        queryWrapper.eq(SpcySqsxWjml::getFwjlx1, WjmlConstant.wjml_type_1_xcjccl);
        queryWrapper.like(SpcySqsxWjml::getFwjlx2, SpcyCommonConstant.SQSX_WJML_TYPE2_BT);
        List<SpcySqsxWjml> mlList = spcySqsxWjmlService.list(queryWrapper);

        if (CollectionUtil.isEmpty(mlList)){
            log.error("现场检查验证材料目录: 业务分类【{}】,目录【{}】,必填【{}】", fywflcode,WjmlConstant.wjml_type_1_xcjccl,SpcyCommonConstant.SQSX_WJML_TYPE2_BT);
            return;
        }

        // 文件记录
        List<WjjlVo> wjjlList = spcySqsxWjjlService.findBtWjjlList(sqsxid, fywflcode, WjmlConstant.wjml_type_1_xcjccl, SpcyCommonConstant.SQSX_WJML_TYPE2_BT);
        if (CollectionUtil.isEmpty(wjjlList)){
            throw new BusinessException("请先完成现场检查相关材料！");
        }

        for (SpcySqsxWjml ml : mlList){
            if (StringUtils.isNotBlank(ml.getFlxmc())){
                List<WjjlVo> mlwjList = wjjlList.stream().filter(q -> ml.getFlxmc().equals(q.getFwjlx1())).collect(Collectors.toList());
                if (CollectionUtil.isEmpty(mlwjList)){
                    throw new BusinessException("请先完成【"+ml.getFlxmc()+"】现场检查材料！");
                }
            }

        }

    }

    /**
     * 验证方案制作-相关材料是否已经存在
     */
    private void verifyFazzFileIsExists(SpcySqsxBasic sqsx, String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            log.error("验证方案制作-相关材料是否已经存在！申请事项参数为空！");
            return;
        }

        /** 查询相关的文件材料 */
        List<String> typeList = CollectionUtil.newArrayList(
                WjmlConstant.jcfa,
                WjmlConstant.xpxcscydh,
                WjmlConstant.xpxcgcydh,
                WjmlConstant.qydwjctz
        );
        List<SpcySqsxWjjl> verifyList = spcySqsxWjjlService.findWjjlJbxxListByFwjlx1(typeList, sqsxid);

        if (CollectionUtil.isEmpty(verifyList)){
            throw new BusinessException("请先制作检查方案及其他材料！");

        }else {

            if (CollectionUtil.isEmpty(
                    verifyList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFwjlx1())
                            && f.getFwjlx1().equals(WjmlConstant.jcfa)
                    )
                    .collect(Collectors.toList())
            )){
                throw new BusinessException("请先制作检查方案材料！");
            }
        }

        /*List<SpcySqsxWjjl> jcfaList = spcySqsxWjjlService.list(new LambdaQueryWrapper<SpcySqsxWjjl>()
                .eq(SpcySqsxWjjl::getFwjlx1, WjmlConstant.jcfa)
                .eq(SpcySqsxWjjl::getFpid, sqsxid));
        if (CollectionUtils.isEmpty(jcfaList)) {
            throw new BusinessException("没有进行制作检查方案，请先制作检查方案！");
        }*/

        String fywflcode = "";
        if (sqsx != null && StringUtils.isNotBlank(sqsx.getFywflcode())) {
            fywflcode = sqsx.getFywflcode();
        }else {
            fywflcode = spcySqsxBaiscService.getYwflCodeBySqsxId(sqsxid);

            if (StringUtils.isBlank(fywflcode)) {
                log.error("业务分类编码为空！申请事项参数{}", sqsxid);
                return;
            }
        }

        if (fywflcode.equals(SpcyConstant.YWFL_CODE_YPSC)){

            if (CollectionUtil.isEmpty(
                    verifyList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFwjlx1())
                                    && f.getFwjlx1().equals(WjmlConstant.xpxcscydh)
                            )
                            .collect(Collectors.toList())
            )){
                throw new BusinessException("请先制作检查员的函材料！");
            }

            if (CollectionUtil.isEmpty(
                    verifyList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFwjlx1())
                                    && f.getFwjlx1().equals(WjmlConstant.xpxcgcydh)
                            )
                            .collect(Collectors.toList())
            )){
                throw new BusinessException("请先制作观察员的函材料！");
            }

            if (CollectionUtil.isEmpty(
                    verifyList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFwjlx1())
                                    && f.getFwjlx1().equals(WjmlConstant.qydwjctz)
                            )
                            .collect(Collectors.toList())
            )){
                throw new BusinessException("请先制作企业通知函材料！");
            }

            /** 验证是否为合并检查 */
            boolean isHbsx = spcyHbjcService.verifySqsxIsHbsqsx(sqsxid, sqsx);
            if (!isHbsx) {
                List<SpcyRsWjmbZjml> zjmlList = spcyRsWjmbZjmlService.selectWjmbZjmlList(sqsxid);
                if (CollectionUtil.isEmpty(zjmlList)) {
                    throw new BusinessException("请选择检查报告模板及章节！");
                }
            }
        }


    }

    /**
     * 验证事项-选派同意人员是否满足
     */
    private void verifyFazzXptyRyNum(String sqsxid){

        // 获取已同意选派人员数量
        SqsxZzZyYbNumVo xpNum = spcySqsxXpjlService.getTyXpZzZyYbNumBean(sqsxid);
        if (xpNum.getFzzrs() == 0){
            throw new BusinessException("请至少选派一名【同意】的组长！");
        }

        // 获取事项预计选派人数
        SqsxZzZyYbNumVo sqsxNum = spcySqsxBaiscService.selectZzZyYbNumBySqsxId(sqsxid);
        if (sqsxNum == null){
            return;
        }else {
            sqsxNum.setFzzrs(Optional.ofNullable(sqsxNum.getFzzrs()).orElseGet(()->0));
            sqsxNum.setFzyrs(Optional.ofNullable(sqsxNum.getFzyrs()).orElseGet(()->0));
            sqsxNum.setFybrs(Optional.ofNullable(sqsxNum.getFybrs()).orElseGet(()->0));
        }

        if ((xpNum.getFzzrs() < sqsxNum.getFzzrs())){
            throw new BusinessException("选派【组长】同意人员不足("+sqsxNum.getFzzrs()+")人！");
        }

        if ((xpNum.getFzyrs() < sqsxNum.getFzyrs())){
            throw new BusinessException("选派【组员】同意人员不足("+sqsxNum.getFzyrs()+")人！");
        }

        if ((xpNum.getFybrs() < sqsxNum.getFybrs())){
            throw new BusinessException("选派【预备检查员】同意人员不足("+sqsxNum.getFybrs()+")人！");
        }
    }

    /**
     * 更新申请事项-查验状态
     */
    private void updateSqsxXcjcCywczt(String sqsxid){
        LambdaUpdateWrapper<SpcySqsxBasic> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcySqsxBasic::getId, sqsxid);

        SpcySqsxBasic updateSqsx = new SpcySqsxBasic();
        updateSqsx.setFcywczt("是");
        spcySqsxBaiscService.update(updateSqsx, updateWrapper);
    }

    /**
     * 更新申请事项-查验方案制作状态
     * @param sqsxid
     */
    private void updateSqsxFazzCyfazt(String sqsxid){
        LambdaUpdateWrapper<SpcySqsxBasic> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcySqsxBasic::getId, sqsxid);

        SpcySqsxBasic updateSqsx = new SpcySqsxBasic();
        updateSqsx.setFcyfazt("是");
        spcySqsxBaiscService.update(updateSqsx, updateWrapper);

    }

    /**
     * 更新未确认选派人员工作状态
     * @param sqsxid
     */
    private void updateSqsxWqrXpryGzzt(String sqsxid){
        List<SpcySqsxXpjl> xpList = spcySqsxXpjlService.getWqrXpXpjlList(sqsxid);
        busService.updateXpryUserGzztInZg(xpList);
    }

    /**
     * 现场检查-给会议设置默认时间
     * @param schy 首次会议
     * @param mchy 末次会议
     */
    public void setDefaultHysjBySqsxId(String sqsxid, boolean schy, boolean mchy){
        spcySqsxYwxxService.setDefaultHysjBySqsxId(sqsxid, schy, mchy);
    }
}
